package com.zx.mes.hyl.test.current;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.lang.Thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * 常用并发类使用
 *
 * @author hyl
 * @date 2018-2-24
 */
public class Current2 {

    private static final Logger logger = Logger.getLogger(Current2.class);
    static CountDownLatch countDownLatch=new CountDownLatch(5);

    @Test
    public void test(){
        for (int i=0;i<5;i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getId()+" 执行");
                    countDownLatch.countDown();
                }
            }).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("五个线程都执行完后，再执行此输出");
    }

    @Test
    public void test2(){
        /**
         * 构造函数参数解释
         * SynchronousQueue、LinkedBlockingQueue (容量无大小,实际有上限)
         * 和ArrayBlockingQueue(初使化时确定了大小,
         * 一旦创建了这样的缓存区，就不能再增加其容量。试图向已满队列中放入元素会导致操作受阻塞；
         * 试图从空队列中提取元素将导致类似阻塞。)
         * @param corePoolSize 线程池维护线程的最少数量
         * @param maximumPoolSize 线程池维护线程的最大数据量
         * @param keepAliveTime 线程池维护线程所允许的空闲时间
         * @param unit 线程池维护线程所允许的空闲时间的单位
         * @param workQueue 线程池所使用的缓冲工作队列
         * @param threadFactory 创建执行线程的工厂
         * @param handler 线程池对拒绝任务的处理策略
         */
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 10, 60, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(10), new MyRejectedExecutionHandler());

        for (int i=0;i<20;i++) {
            tpe.execute(new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(Math.abs((int)Math.random()*100));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    logger.debug(JSON.toJSONStringWithDateFormat("执行的线程:"+Thread.currentThread().getId(),"yyyy-MM-dd HH:mm:ss"));
                }
            }));
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}
